package com.digital.community;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.digital.community.common.bean.CommonBean;
import com.digital.community.common.utils.HttpDownloader;
import com.digital.community.common.utils.HttpUtils;
import com.digital.community.common.utils.StringUtils;
import com.digital.community.common.utils.ToastUtils;

public class LoginActivity extends Activity {
    
	private EditText nameET;
	private EditText pwdEt;
	private CheckBox remberCheck;
	CommonBean commonBean;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        init();
    }
    
	@Override
	protected void onStart() {
		super.onStart();
		commonBean = (CommonBean)getApplicationContext();
		if(commonBean.isClose()) {
			finish();
		}
	}
    
    private LinearLayout lyout1;
    private RelativeLayout lyout2;
	private void init() {
		lyout1 = (LinearLayout)findViewById(R.id.lyout1);
		lyout2 = (RelativeLayout)findViewById(R.id.lyout2);
		
		nameET = (EditText)findViewById(R.id.et_name);
		pwdEt = (EditText)findViewById(R.id.et_pwd);
		remberCheck = (CheckBox)findViewById(R.id.chk_remember_pwd);
		
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		nameET.setText(sp.getString("lname", ""));
		nameET.setSelection((sp.getString("lname", "")).length());
		pwdEt.setText(sp.getString("lpwd", ""));
		pwdEt.setSelection((sp.getString("lpwd", "")).length());
		remberCheck.setChecked(sp.getBoolean("remeberAccount", false));
	}
	
	
	private String name = null;
	private String pwd = null;
	public void login(View view) {
		name = nameET.getText().toString();
		pwd = pwdEt.getText().toString();
		
		if(StringUtils.isBlank(name) || StringUtils.isBlank(pwd)) {
			ToastUtils.showErrorToast(this, getLayoutInflater(), "帐号或者密码不能为空!", false);
			return;
		}
		
		toLogin();
	}
	
	private String uguid;
	private ArrayList<String> nationList;
	private ArrayList<String> cardtypeList;
	private ArrayList<String> genderList;
	ProgressDialog proDialog;
	private void toLogin() {
		proDialog = ProgressDialog.show(LoginActivity.this, "请等待", "正在请求数据...",true,true);
		
		new Thread() {
			public void run() {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("name", name);
				params.put("pwd", pwd);
				Bundle bundle = HttpUtils.getPost("login.do", params, 3000, LoginActivity.this);
				
				if(bundle.getInt("code") == HttpUtils.SUCCESS) {
					String content = bundle.getString("content");
					System.out.println("content: " + content);
					if(StringUtils.isBlank(content) || "[]".equals(content)) {
						handler.sendEmptyMessage(HANLER_CONN_ERROR);
						return;
					} else {
						try {
							JSONArray arr = new JSONArray(content);
							int success = 0;
							if(arr.length() > 0) {
								JSONObject resultArr = arr.getJSONObject(0);
								success = resultArr.getInt("success");
								uguid = resultArr.getString("uguid");
							}
							if(success == 1) {
								JSONArray nationArr = arr.getJSONArray(1);
								JSONArray cardtypeArr = arr.getJSONArray(2);
								JSONArray genderArr = arr.getJSONArray(3);
								
								nationList = new ArrayList<String>();
								cardtypeList = new ArrayList<String>();
								genderList = new ArrayList<String>();
								
								if(nationArr != null && nationArr.length() > 0) {
									for(int i = 0; i < nationArr.length(); i ++) {
										nationList.add(nationArr.getString(i));
									}
								}
								if(cardtypeArr != null && cardtypeArr.length() > 0) {
									for(int i = 0; i < cardtypeArr.length(); i ++) {
										cardtypeList.add(cardtypeArr.getString(i));
									}
								}
								if(genderArr != null && genderArr.length() > 0) {
									for(int i = 0; i < genderArr.length(); i ++) {
										genderList.add(genderArr.getString(i));
									}
								}
								
								handler.sendEmptyMessage(HANLER_LOGIN_SUCCESS);
								commonBean.setName(name);
								
							} else {
								handler.sendEmptyMessage(HANLER_LOGIN_FAILD);
							}
						} catch (Exception e) {
							System.out.println(e);
							
							handler.sendEmptyMessage(HANLER_CONN_ERROR);
						}
					}
				} else {
					handler.sendEmptyMessage(HANLER_CONN_ERROR);
				}
			};
		}.start();
	}
	
	private static final int HANLER_CONN_ERROR = 1;
	private static final int HANLER_LOGIN_SUCCESS = 2;
	private static final int HANLER_LOGIN_FAILD = 3;
	private static final int HANLER_UPDATE_CONN_ERROR = 4;
	private static final int HANLER_NOT_NEED_UPDATE = 5;
	private static final int HANLER_NEED_UPDATE = 6;
	private static final int HANDLER_DOWNLOAD_APP = 7;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(proDialog != null && proDialog.isShowing()) {
				proDialog.dismiss();
			}
			
			switch (msg.what) {
			case HANLER_CONN_ERROR:
				showDialog(DIALOG_NETWORK_ERROR);
				break;
			case HANLER_LOGIN_SUCCESS:
				//保存
				Editor editor = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this).edit();
				editor.putBoolean("remeberAccount", remberCheck.isChecked());
				if(remberCheck.isChecked()) {
					editor.putString("lname", name);
					editor.putString("lpwd", pwd);
				}
		    	editor.commit();
		    	
				Intent intent = new Intent(LoginActivity.this, HallActivity.class);
				intent.putStringArrayListExtra("nation", nationList);
				intent.putStringArrayListExtra("cardtype", cardtypeList);
				intent.putStringArrayListExtra("gender", genderList);
				intent.putExtra("uguid", uguid);
				startActivity(intent);
				finish();
				break;
			case HANLER_LOGIN_FAILD:
				ToastUtils.showErrorToast(LoginActivity.this, getLayoutInflater(), "帐号或密码错误!", false);
				break;
			case HANLER_UPDATE_CONN_ERROR:
				showDialog(DIALOG_UPDATE_CONN_ERROR);
				break;
			case HANLER_NOT_NEED_UPDATE:
				ToastUtils.showTrueToast(LoginActivity.this, getLayoutInflater(), "客户端已经是最新的了!", false);
				break;
			case HANLER_NEED_UPDATE:
				showDialog(DIALOG_NEED_UPDATE);
				break;
			case HANDLER_DOWNLOAD_APP:
				int iRet2 = msg.arg1;
				proDialog.dismiss();
				if(iRet2 == 0) {//下载成功
					Toast.makeText(LoginActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
					
					//安装新的应用
					Intent intent2 = new Intent(Intent.ACTION_VIEW);   
					String filePath = "/sdcard/" + tempFileName;   
					intent2.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");
					LoginActivity.this.startActivity(intent2);
				} else if(iRet2 == -2) {//SDCard不存在
					showDialog(DIALOG_NO_SDCARD);
				} else if(iRet2 == -1) {//下载失败
					showDialog(DIALOG_DOWNLOAD_FAILED);
				}
			break;
			default:
				break;
			}
			
			
		};
	};
	
	
	private static final int DIALOG_NETWORK_ERROR = 200;
	private static final int DIALOG_NEED_UPDATE = 201;
	private static final int DIALOG_UPDATE_CONN_ERROR = 202;
	private static final int DIALOG_NO_SDCARD = 203;
	private static final int DIALOG_DOWNLOAD_FAILED = 204;
	@Override
	protected Dialog onCreateDialog(int id) {
		if(!isActive) return null;
		switch (id) {
		case DIALOG_NETWORK_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
			.setPositiveButton("重试", new Retry())
			.setNegativeButton("取消", new Cancle()).create();
		case DIALOG_UPDATE_CONN_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
			.setPositiveButton("重试", new RetryUpdate())
			.setNegativeButton("取消", new Cancle()).create();
		case DIALOG_NEED_UPDATE:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("是否更新客户端?")
			.setPositiveButton("重试", new Update())
			.setNegativeButton("取消", new Cancle()).create();
		case DIALOG_NO_SDCARD:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("SD卡不存在!")
						.setPositiveButton("确定", new Cancle()).create();
		case DIALOG_DOWNLOAD_FAILED:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,下载失败,是否重试?")
			.setPositiveButton("重试", new Redownload())
			.setNegativeButton("取消", new Cancle()).create();
			
		default:
			return null;
		}
		
	}
	
	private class Retry implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			toLogin();
		}
	}
	private class RetryUpdate implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			toCheck();
		}
	}
	private class Redownload implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			downoApp();
		}
	}
	private class Cancle implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		}
	}
	private String tempFileName;
	private class Update implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			tempFileName = "szdx_door.apk";
			downoApp();
		}
	}
	
	private boolean isActive = true;
	@Override
	protected void onDestroy() {
		isActive = false;
		
		super.onDestroy();
	}
    
	boolean lyout2IsShowing = false;
	public void show(View view) {
		lyout2IsShowing = true;
		lyout2.setVisibility(View.VISIBLE);
	}
	
    public void dismiss(View view) {
    	lyout2IsShowing = false;
    	lyout2.setVisibility(View.GONE);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if(keyCode == KeyEvent.KEYCODE_BACK && lyout2IsShowing) {
    		dismiss(null);
    	} else {
    		finish();
    	}
    	
    	return true;
    }
    
    public void clearAccount(View view) {
    	dismiss(null);
    	
    	SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    	Editor editor = sp.edit();
    	editor.putString("lname", "");
    	editor.putString("lpwd", "");
    	editor.commit();
    	
    	ToastUtils.showTrueToast(this, getLayoutInflater(), "帐号清除成功!", false);
    }
    
    public void setIp(View view) {
    	dismiss(null);
    	Intent intent = new Intent(this, IPSetActivity.class);
		startActivity(intent);
    }
    
    public void checkUpdate(View view) {
    	toCheck();
    	dismiss(null);
    }
    
    private void toCheck() {
    	proDialog = ProgressDialog.show(LoginActivity.this, "请等待", "正在请求数据...",true,true);
    	new Thread() {
    		public void run() {
    			Bundle bundle = HttpUtils.getPost("update.do", null, 3000, LoginActivity.this);
    			if(bundle.getInt("code") == HttpUtils.SUCCESS) {
					String content = bundle.getString("content");
					if(StringUtils.isBlank(content) || "{}".equals(content)) {
						handler.sendEmptyMessage(HANLER_UPDATE_CONN_ERROR);
						return;
					} else {
						try {
							JSONObject json = new JSONObject(content);
							String serverVer = json.getString("ver");
							
							
							PackageInfo pkgInfo = getPackageManager().getPackageInfo(LoginActivity.this.getPackageName(), 0);
							String appVer = pkgInfo.versionName;
							
							if(serverVer.compareTo(appVer) > 0) {
								handler.sendEmptyMessage(HANLER_NEED_UPDATE);
							} else {
								handler.sendEmptyMessage(HANLER_NOT_NEED_UPDATE);
							}
						} catch (Exception e) {
							System.out.println(e);
							
							handler.sendEmptyMessage(HANLER_CONN_ERROR);
						}
					}
				} else {
					handler.sendEmptyMessage(HANLER_CONN_ERROR);
				}
    			
    		};
    	}.start();
    }
    
    public void toExit(View view) {
//    	CommonBean commonBean = (CommonBean)getApplicationContext();
//    	commonBean.setClose(true);
    	finish();
    }
    
	/**
	 * 下载别的新应用
	 */
	private void downoApp() {
		proDialog = ProgressDialog.show(LoginActivity.this, "请等待", "正在处理中...",true,true);
		new Thread() {
			public void run() {
				HttpDownloader httpDownloader = new HttpDownloader(LoginActivity.this);
				int iRet = httpDownloader.downloadFileToSDCard(tempFileName);
				
				Message msg = handler.obtainMessage();
				msg.arg1 = iRet;
				msg.what = HANDLER_DOWNLOAD_APP;
				handler.sendMessage(msg);
			};
		}.start();
	}
}